package com.chengz.main;

import com.chengz.bo.Student;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class TestFileds {


    public static void main(String[] args) {

        /*
         * 获取成员变量并调用：
         *
         * 1.批量的
         *      1).Field[] getFields():获取所有的”公有字段”
         *      2).Field[] getDeclaredFields():获取所有字段，包括：私有、受保护、默认、公有；
         * 2.获取单个的：
         *      1).public Field getField(String fieldName):获取某个”公有的”字段；
         *      2).public Field getDeclaredField(String fieldName):获取某个字段(可以是私有的)
         *
         *   设置字段的值：
         *      Field –> public void set(Object obj,Object value):
         *                  参数说明：
         *                  1.obj:要设置的字段所在的对象；
         *                  2.value:要为字段设置的值；
         *
         */

        try {
            Class clazz=Class.forName("com.chengz.bo.Student");

            Field [] fields= clazz.getFields();
            for(Field field:fields){
                System.out.println(field);
            }

            System.out.println(" >>>>>>>>>>>>>>>>>>>>我是分割线>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");

            Field [] allfields=clazz.getDeclaredFields();
            for (Field field: allfields){
                System.out.println(field);
            }


            System.out.println(" >>>>>>>>>>>>>>>>>>>>我是分割线>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            Field nameField=clazz.getField("name");
            System.out.println(nameField);


            //给对象赋值
            //产生Student 对象
            Object obj=clazz.getConstructor().newInstance();
            nameField.set(obj,"亚芬");



            Field sexField=clazz.getDeclaredField("sex");
            Field ageField=clazz.getDeclaredField("age");
            Field phonenumField=clazz.getDeclaredField("phonenum");

            //暴力反射
            sexField.setAccessible(true);
            sexField.set(obj,'男');

            ageField.setAccessible(true);
            ageField.set(obj,28);

            phonenumField.setAccessible(true);
            phonenumField.set(obj,"(^_^)／");
            Student s= (Student) obj;

            System.out.println(s.name);
            System.out.println(s);

            //获取私有变量




        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }


    }



}
